import re

from django_redis import get_redis_connection
from rest_framework import serializers

from celery_tasks.email.tasks import send_verify_email
from goods.models import SKU
from users import constants
from users.models import User, Address


class CreateUserSerializer(serializers.ModelSerializer):
    '''
        创建序列化器
    '''

    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)  # True
    token = serializers.CharField(label='JWT token', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'password2', 'mobile', 'sms_code', 'allow', 'token')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        """验证手机号"""
        # 验证格式
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        # 验证是否重复
        count = User.objects.filter(mobile=value).count()
        if count > 0:
            raise serializers.ValidationError('手机号已存在')

        return value

    def validate_allow(self, value):
        """检验用户是否同意协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, data):
        '''
        # 判断两次密码
        '''
        if data['password'] != data['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 验证手机验证码
        # 1.连接radis
        redis_conn = get_redis_connection('verify_codes')

        # 2. 用data里的电话号码取到验证码
        mobile = data['mobile']
        sms_code = redis_conn.get('sme_%s' % mobile)

        # 3. 然后对比验证
        if sms_code is None:
            raise serializers.ValidationError('短信验证码无效')

        if data['sms_code'] != sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return data

    # 注册

    def create(self, validated_data):
        """
           创建用户
           validated_data验证后的数据
        """
        # 移除数据库模型类中不存在的属性
        del validated_data['password2']
        del validated_data['allow']
        del validated_data['sms_code']

        # 创建新用户
        user = User.objects.create_user(**validated_data)
        # 服务器生成jwt 保存用户数据
        from rest_framework_jwt.settings import api_settings
        # 生成载荷
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成JWT token
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        print(payload)
        token = jwt_encode_handler(payload)

        user.token = token
        print(token)

        return user


# 用户详情
class UserDetailSerializer(serializers.ModelSerializer):
    '''
    用户详情
    '''

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


# 设置邮箱及验证邮箱
class EmailSerializer(serializers.ModelSerializer):
    '''# 设置邮箱及验证邮箱'''

    class Meta:
        model = User
        fields = ('id', 'email')

    def update(self, instance, validated_data):
        '''
        保存邮箱地址 & 发送验证邮件到用户
        '''
        # 保存邮箱地址
        email = validated_data['email']
        instance.email = email
        instance.save()
        # 发送验证链接邮件到用户
        # 1. 生成验证链接,加入加密后的用户信息加如链接
        verify_url = instance.generate_verify_email()
        # 2. 利用celery异步发邮件
        send_verify_email.delay(email, verify_url)
        return instance


# 新增收货地址
class UserAddressSerializer(serializers.ModelSerializer):
    '''地址序列化器'''
    province_id = serializers.IntegerField(label='省id')
    city_id = serializers.IntegerField(label='市id')
    district_id = serializers.IntegerField(label='区id')

    province = serializers.StringRelatedField(label='省名称', read_only=True)
    city = serializers.StringRelatedField(label='市名称', read_only=True)
    district = serializers.StringRelatedField(label='区名称', read_only=True)

    class Meta:
        model = Address
        exclude = ('is_deleted', "user", "create_time", "update_time")

    def validate_mobile(self, value):
        '''验证手机号格式是否正确'''
        if not re.match(r'^1[3-9]\d{9}$', value):
            return serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        '''添加用户地址'''
        user = self.context['request'].user
        validated_data['user'] = user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """

    class Meta:
        model = Address
        fields = ('title',)


# 历史浏览
class HistorySeralizer(serializers.Serializer):
    '''历史浏览记录序列化器类'''
    sku_id = serializers.IntegerField(label='sku商品id', min_value=1)

    def validate_sku_id(self, value):
        '''对sku_id 进行校验 商品是否存在'''
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value

    def create(self, validated_data):
        '''
        在redis中保存登录用户的浏览记录
        1. 去重(如果商品已经被浏览过,先从redis中将sku_id删除)
        2. 保持浏览记录顺序(最新浏览记录从列表左侧添加)
        3. 截取(只保留浏览记录最近的5条商品id)
        '''
        # 1. 去重(如果商品已经被浏览过,先从redis中将sku_id删除)
        redis_conn = get_redis_connection('histores')
        # 拼接key
        user = self.context['request'].user
        history_key = "history_%s" % user.id
        sku_id = validated_data['sku_id']
        # 利用管道一次执行命令
        pl = redis_conn.pipeline()

        pl.lrem(history_key, 0, sku_id)

        # 2. 保持浏览记录顺序(最新浏览记录从列表左侧添加)
        pl.lpush(history_key, sku_id)

        # 3. 截取(只保留浏览记录最近的5条商品id)
        pl.ltrim(history_key, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)

        pl.execute()

        return validated_data
